package com.aiguigu;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SyncVsLockDemo {

    public synchronized void m1() {
        System.out.println(Thread.currentThread().getName() + "------come in");

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    Lock lock = new ReentrantLock();

    public void m2() {
        if (lock.tryLock()) {
            try {
                System.out.println(Thread.currentThread().getName() + "------come in");

            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "------抢锁失败");
        }
    }

    public void m3() {
        try {
            if (lock.tryLock(2L,TimeUnit.SECONDS)) {
                try {
                    System.out.println(Thread.currentThread().getName() + "------come in");
                    try {
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } finally {
                    lock.unlock();
                }
            } else {
                System.out.println(Thread.currentThread().getName() + "------抢锁失败");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) {
        SyncVsLockDemo syncVsLockDemo = new SyncVsLockDemo();

        //synchronized没有锁退出机制 只能等待一个执行完毕另一个在执行
        /*new Thread(()->{syncVsLockDemo.m1();},"t1").start();
        new Thread(()->{syncVsLockDemo.m1();},"t2").start();*/

        //lock.tryLock()有锁退出机制  抢不到退出
        new Thread(() -> {syncVsLockDemo.m2();}, "t1").start();
        new Thread(() -> {syncVsLockDemo.m2();}, "t2").start();
        //tryLock(long time, TimeUnit unit)  可以设置等待时间
        new Thread(() -> {syncVsLockDemo.m3();}, "t1").start();
        new Thread(() -> {syncVsLockDemo.m3();}, "t2").start();
    }
}
